﻿#include "game_object.h"

GameObject::GameObject():
pattern_params(0), control_cycle(0), params_passed(0)
{
}

GameObject::~GameObject()
{
	if (pattern_params)
		delete[] pattern_params;
}

bool GameObject::Collide(GameObject *other)
{
	// calculate relative velocity and position
	CL_Vec2<float> dv = (other->position - other->prev_position) - (position - prev_position);
	CL_Vec2<float> dp = other->prev_position - prev_position;

    // check if circles are already colliding
	float r = collision_size + other->collision_size;
	float pp = dp.x * dp.x + dp.y * dp.y - r * r;
    if(pp < 0)
		return true; 

    // check if the circles are moving away from each other and hence can’t collide
    float pv = dp.x * dv.x + dp.y * dv.y;
    if(pv >= 0) 
		return false;

    // check if the circles can reach each other between the frames
    float vv = dv.x * dv.x + dv.y * dv.y;
	if ( ((pv + vv) <= 0) && (vv + 2 * pv + pp) >= 0 ) 
		return false;

    // if we've gotten this far then it’s possible for intersection if the distance between
    // the circles is less than the radii sum when it’s at a minimum. Therefore find the time
    // when the distance is at a minimum and test this
    // float tmin = -pv / vv;
	// Discriminant/(4*dV^2) = -(dp^2-r^2+dP*dV*tmin)
    // return ( (pp + pv * tmin) > 0 );
	//if ( (pv * pv - pp * vv) > 0)
	//{
	//	cl_log_event("Debug", "============ Collision happened ! =============");
	//	cl_log_event("Debug", "Colliding bullet at  x = %1 , y = %2  --- was at x_ = %3 , y_ = %4", position.x, position.y, prev_position.x, prev_position.y);
	//	cl_log_event("Debug", "With player at  x = %1 , y = %2  --- was at x_ = %3 , y_ = %4", other->position.x, other->position.y, other->prev_position.x, other->prev_position.y);
	//	cl_log_event("Debug", "Bullet collision size = %1     -------------   Player collision size = %2", collision_size, other->collision_size);
	//	cl_log_event("Debug", "=== 2. Circles collided while moving ===");
	//	cl_log_event("Debug", "===============================================");
	//}
	return ( (pv * pv - pp * vv) > 0);
}
